/*
 * @Author: your name
 * @Date: 2021-05-31 17:05:17
 * @LastEditTime: 2021-05-31 18:33:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /xiangpan-admin/src/components/countDown/index.tsx
 */
// import { useEffect, useState } from 'react';

import { secondsToMinSec } from '@/utils/utils';
import moment from 'moment';
import React from 'react';
import { useEffect, useMemo, useState } from 'react';

interface CountDownProps {
  total: number; // 倒计时的时间，单位毫秒
  endTime?: number; // 结束的时间点，与 total 二选一，且优先级更高，单位毫秒
  format?: string | ((progress: number) => string); // 要展示的时间格式，可以是字符串或者函数
  diff?: number; // 频率，单位毫秒ms
  onStart?: () => void; // 开始时的回调
  onStep?: (step: number) => void; // 每次更新时执行的回调
  onEnd?: () => void; // 结束时的回调
}
const CountDown = (props: CountDownProps) => {
  const endTime = useMemo(() => Date.now() + 1000 * props.total, []); // 持续10s的时间
  const [leftTime, setLeftTime] = useState(0);

  useEffect(() => {
    const count = () => {
      let now = Date.now();
      const diff = endTime - now;
      if (diff >= 0) {
        setLeftTime((diff / 1000).toFixed(0));
        requestAnimationFrame(count);
      } else {
        setLeftTime(0);
      }
    };
    count();
    return () => {
      setLeftTime(0);
    };
  }, [endTime]);

  return <span>{secondsToMinSec(leftTime)}</span>;
};

export default CountDown;
